package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: atguigu
 * @create: 2023-12-08 10:24
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;


    /**
     * 将图片文件上传到MInIO
     *
     * @param file 图片文件
     * @return 上传后图片在线地址
     */
    @Override
    public String imageUpload(MultipartFile file) {
        try {
            //1.业务校验验证文件是否为图片 借助ImageIO读取图片 继续判断图片文件后缀名是否符合要求
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new GuiguException(400, "图片格式非法！");
            }

            //2.调用MInIO-Java客户端对象将文件上传到MInIO-文件上传
            //2.1 动态生成上传文件名称 /当日日期/UUID.后缀
            String folderName = "/" + DateUtil.today() + "/";
            String fileName = IdUtil.randomUUID();
            String extName = FileUtil.extName(file.getOriginalFilename());  //
            String objectName = folderName + fileName + "." + extName;
            // a.png
            //2.2 调用文件上传接口
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //3.拼接上传文件成功后在线地址 http://ip:9000/存储空间名称/路径/文件标识名称
            return props.getEndpointUrl()+"/"+props.getBucketName()+objectName;
        } catch (Exception e) {
            log.error("[专辑服务]上传图片文件异常：{}", e);
            throw new RuntimeException(e);
        }
    }
}
